package com.ishopping.common.core.utils.tree;

import com.ishopping.common.core.vo.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取树节点集合
 */
public class TreeNodeUtils {
    /**
     * 完善节点数据
     * @param treeNodeList
     * @return List<TreeNode>
     */
    public static List<TreeNode> getFatherNodes(List<TreeNode> treeNodeList) {
        List<TreeNode> newTreeNodeList = new ArrayList<TreeNode>();
        for (TreeNode treeNode : treeNodeList) {
            //父节点为空表示该节点为父节点
            if(treeNode.getParentId() == null) {
                //获取父节点下的子节点
                treeNode.setChildren(getChildrenNodes(treeNode.getId(), treeNodeList));
                treeNode.setState("open");
                newTreeNodeList.add(treeNode);
            }
        }
        return newTreeNodeList;
    }

    /**
     * 获取孩子节点列表
     * @param parentId
     * @param treeNodeList
     * @return List<TreeNode>
     */
    private static List<TreeNode> getChildrenNodes(Long parentId , List<TreeNode> treeNodeList) {
        List<TreeNode> childNodeList = new ArrayList<TreeNode>();
        for (TreeNode treeNode : treeNodeList) {
            if(treeNode.getParentId() == null) {
                continue;
            }
            //这是一个子节点
            if(treeNode.getParentId().equals(parentId)){
                //递归获取子节点下的子节点
                treeNode.setChildren(getChildrenNodes(treeNode.getId(), treeNodeList));
                childNodeList.add(treeNode);
            }
        }
        return childNodeList;
    }
}
